﻿using System;
using System.Collections.Generic;
using System.Threading.Tasks;
using Thinker.SignChannel.Entities;
using Thinker.SignChannel.Repositories;
using Volo.Abp.DependencyInjection;
using Volo.Abp.Domain.Repositories;
using Volo.Abp.Uow;

namespace Thinker.SignChannel.Results;

public class PersonTimeCreator(
    IPersonTimeRepository personTimeRepository,
    IPersonRepository personRepository) : ITransientDependency
{
    public async Task<PersonTime> GetOrCreateAsync(Guid personId, Guid timeId)
    {
        var personTime = await personTimeRepository.FindByKeyAsync(personId, timeId);
        if (personTime != null)
        {
            return personTime;
        }

        personTime = new PersonTime(Guid.NewGuid(), personId, timeId);
        return await personTimeRepository.InsertAsync(personTime, true);
    }

    [UnitOfWork]
    public virtual async Task BuildAllAsync(Guid timeId)
    {
        var people = await personRepository.GetListAsync();

        var list = new List<PersonTime>();
        foreach (var person in people)
        {
            var personId = person.Id;
            var personTime = await personTimeRepository.FindByKeyAsync(personId, timeId);
            if (personTime != null)
            {
                continue;
            }

            personTime = new PersonTime(Guid.NewGuid(), personId, timeId);
            list.Add(personTime);
        }

        await personTimeRepository.InsertManyAsync(list, true);
    }

    [UnitOfWork]
    public virtual async Task BuildAllIfNotAsync(Guid timeId)
    {
        if (await personTimeRepository.CountAsync(x => x.TimeId == timeId) > 0)
        {
            return;
        }

        await BuildAllAsync(timeId);
    }
}